const { ethers } = require("hardhat");

async function main() {
    console.log("测试新的联合曲线计算...");

    // 获取合约工厂
    const XLayerLaunchPad = await ethers.getContractFactory("XLayerLaunchPad");
    
    // 部署合约（使用测试路由器地址）
    const testRouterAddress = "0x1234567890123456789012345678901234567890"; // 占位地址
    const launchPad = await XLayerLaunchPad.deploy(testRouterAddress);
    await launchPad.waitForDeployment();

    console.log("LaunchPad 合约已部署到:", await launchPad.getAddress());

    // 获取合约参数
    const basePrice = await launchPad.CURVE_BASE_PRICE();
    const priceIncrement = await launchPad.CURVE_PRICE_INCREMENT();
    const tokensForCurve = await launchPad.TOKENS_FOR_CURVE();

    console.log("联合曲线参数:");
    console.log("- 基础价格:", basePrice.toString());
    console.log("- 价格增量:", priceIncrement.toString());
    console.log("- 曲线代币总量:", ethers.formatEther(tokensForCurve));

    // 测试场景：当没有代币售出时的初始价格
    console.log("\n=== 测试场景 1: 初始状态 ===");
    const initialPrice = basePrice + (BigInt(0) * priceIncrement) / BigInt(10**18);
    console.log("初始价格 (每个代币):", initialPrice.toString(), "wei");

    // 测试场景：计算购买 1 ETH 可以获得多少代币
    console.log("\n=== 测试场景 2: 购买 1 ETH ===");
    const ethAmount = ethers.parseEther("1");
    
    // 使用二次方程求解
    const A = priceIncrement;
    const B = BigInt(2) * initialPrice * BigInt(10**18);
    const C = BigInt(2) * ethAmount * BigInt(10**36);
    
    const discriminant = B * B + BigInt(4) * A * C;
    const sqrtDiscriminant = sqrt(discriminant);
    
    if (sqrtDiscriminant >= B) {
        const tokensReceived = (sqrtDiscriminant - B) / (BigInt(2) * A);
        console.log("使用 1 ETH 可购买代币数量:", ethers.formatEther(tokensReceived));
        
        // 验证：计算购买这些代币的实际成本
        const actualCost = (initialPrice * tokensReceived + (priceIncrement * tokensReceived * tokensReceived) / (BigInt(2) * BigInt(10**18))) / BigInt(10**18);
        console.log("实际成本:", ethers.formatEther(actualCost), "ETH");
        console.log("误差:", ethers.formatEther(ethAmount - actualCost), "ETH");
    }

    console.log("\n联合曲线计算测试完成！");
}

// 简单的整数平方根函数
function sqrt(value) {
    if (value < 0n) {
        throw new Error('square root of negative numbers is not supported');
    }

    if (value < 2n) {
        return value;
    }

    function newtonIteration(n, x0) {
        const x1 = ((n / x0) + x0) >> 1n;
        if (x0 === x1 || x0 === (x1 - 1n)) {
            return x0;
        }
        return newtonIteration(n, x1);
    }

    return newtonIteration(value, 1n);
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error);
        process.exit(1);
    });
